package service

import (
	"context"
	"qld2devservice/cons"
	"qld2devservice/proto"
	"qld2devservice/utils"

	"google.golang.org/grpc"
)

var (
	ADDRESS_MQTT = "qld2mqttservice:8306"
)

func init() {
	if cons.GRPC_TEST_MODE == cons.ENUM_SERVER {
	} else if cons.GRPC_TEST_MODE == cons.ENUM_SERVER_TEST {
	} else if cons.GRPC_TEST_MODE == cons.ENUM_LOCALHOST {
		ADDRESS_MQTT = "192.168.100.99:8306"
	}
}

func MqttCmdDevice(sendTopic, recvTopic, cmdStr string, repeatNum, timeOutSecond int64) (response string, timeOutFlag bool, err error) {
	// 连接到 gRPC 服务器
	conn, err := grpc.Dial(ADDRESS_MQTT, grpc.WithInsecure())
	if err != nil {
		errNew := utils.WrapError(err, "MqttCmdDevice,gRPC服务器连接失败,"+sendTopic+","+cmdStr)
		utils.MyPrint(utils.PRINT_ERROR, errNew.Msg())
		return "", false, errNew
	}
	defer conn.Close()

	// 初始化 gRPC 客户端
	client := proto.NewMqttClient(conn)
	res := proto.MqttCmdRequest{
		CmdSendTopic:  sendTopic,
		CmdRecvTopic:  recvTopic,
		CmdStr:        cmdStr,
		RepeatNum:     repeatNum,
		TimeOutSecond: timeOutSecond,
	}
	utils.MyPrint(utils.PRINT_INFO, "MqttCmd request", res)
	resp, err := client.MqttCmd(context.Background(), &res)
	if err != nil {
		errNew := utils.WrapError(err, "MqttCmdDevice的gRPC调用失败,"+sendTopic+","+cmdStr)
		utils.MyPrint(utils.PRINT_ERROR, errNew.Msg())
		return "", false, errNew
	}
	utils.MyPrint(utils.PRINT_INFO, "MqttCmd response", utils.TransProtoToJson(resp))
	return resp.CmdResponse, resp.TimeOut, nil
}
